package com.ecarx.library_base.usb.brodcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.ecarx.library_base.usb.UDiskDevice;
import com.ecarx.library_base.usb.UDiskUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 监听U盘插拔事件
 */
public class USBReceiver extends BroadcastReceiver {

    private static final String TAG = "USBReceiver";

    private final UsbChangeCallback usbChangeCallback;
    List<UDiskDevice> cacheList = new ArrayList<>();


    public USBReceiver(UsbChangeCallback usbChangeCallback) {
        this.usbChangeCallback = usbChangeCallback;
        cacheList.addAll(UDiskUtil.getUDiskDeviceList());
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: " + intent.toString() + " data :"+  intent.getDataString());
        List<UDiskDevice> uDiskDeviceList = UDiskUtil.getUDiskDeviceList();
        if (cacheList.size() == uDiskDeviceList.size() && cacheList.containsAll(uDiskDeviceList)) {
            return;
        }
        cacheList.clear();
        cacheList.addAll(uDiskDeviceList);

        switch (intent.getAction()) {
            case Intent.ACTION_MEDIA_MOUNTED: {
                usbChangeCallback.onUsbDeviceChanged(true, uDiskDeviceList);
                break;
            }
            case Intent.ACTION_MEDIA_BAD_REMOVAL: {
                usbChangeCallback.onUsbDeviceChanged(false, uDiskDeviceList);
                break;
            }
            default:
                break;
        }


    }

    public interface UsbChangeCallback {

        /**
         * U盘插拔事件回调
         * @param isAdd 添加/卸载
         * @param uDiskDeviceList 所有U盘
         */
        void onUsbDeviceChanged(boolean isAdd, List<UDiskDevice> uDiskDeviceList);

    }

}

